package com.starblink.android.basic.network.base

import android.content.Context
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.starblink.android.basic.base.BaseApplication
import com.starblink.android.basic.bridge.BridgeCommand
import com.starblink.android.basic.bridge.BridgeUtil
import com.starblink.android.basic.config.GuangConfig
import com.starblink.android.basic.ext.ToastBussUtils
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.storage.SkStorage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.fragment.SiteVOF
import java.io.BufferedInputStream


/**
 * from flutter project sk_net_cfg.dart
 */

object BaseApiConfig {

    private const val SITE_DEFAULT = "DEFAULT"
    //非默认站点
    val SITE_NOT_NOT_DEFAULT = ApiSiteEnum.GB.name
    /**根据build.gradle 里的productFlavors去判断默认的网络切换选择（初始化没有mmkv配置及json配置读取失败的情况下兜底）*/
    const val DEFAULT_FLAVOR = "play"
    const val TEST_CI_FLAVOR = "ci"

    const val GB_PUB_TRACK_URL = "https://front-log-v1.starblink.co/app"
    const val US_PUB_TRACK_URL = "https://us-front-log-v1.starblink.co/app"


    // pub 生产环境
    private val pubEnv = mapOf(
        BaseApiCodeAndUrl.NAME to "pub",
        BaseApiCodeAndUrl.DESC to "生产环境",
        BaseApiCodeAndUrl.HOST to "https://guang.starblink.co",
        BaseApiCodeAndUrl.URL to "https://guang.starblink.co/graphql",
        BaseApiCodeAndUrl.LOG_URL to "https://front-log.starblink.co/app",
        BaseApiCodeAndUrl.H5_HOST to "https://getguang.com/",
//        BaseApiCodeAndUrl.TRACK_URL to "https://front-log-v1.starblink.co/app",
        BaseApiCodeAndUrl.TRACK_URL to GB_PUB_TRACK_URL,
        BaseApiCodeAndUrl.ENABLE to true,
        BaseApiCodeAndUrl.SITE to SITE_NOT_NOT_DEFAULT
    )

    // pre 预发环境
    private val preEnv = mapOf(
        BaseApiCodeAndUrl.NAME to "pre",
        BaseApiCodeAndUrl.DESC to "预发环境",
        BaseApiCodeAndUrl.HOST to "https://pre-guang.starblink.co",
        BaseApiCodeAndUrl.URL to "https://pre-guang.starblink.co/graphql",
        BaseApiCodeAndUrl.LOG_URL to "https://pre-front-log.starblink.co/app",
        BaseApiCodeAndUrl.H5_HOST to "https://pre-www.getguang.com/",
        BaseApiCodeAndUrl.TRACK_URL to "https://pre-front-log-v1.starblink.co/app",
        BaseApiCodeAndUrl.ENABLE to true,
        BaseApiCodeAndUrl.SITE to SITE_DEFAULT
    )

    // test 测试环境
    private val testEnv = mapOf(
        BaseApiCodeAndUrl.NAME to "test",
        BaseApiCodeAndUrl.DESC to "测试环境",
        BaseApiCodeAndUrl.HOST to "https://guang-test.starblink.co",
        BaseApiCodeAndUrl.URL to "https://guang-test.starblink.co/graphql",
        BaseApiCodeAndUrl.LOG_URL to "https://test-front-log.starblink.co/app",
        BaseApiCodeAndUrl.H5_HOST to "https://test-getguang-com.starblink.co/",
        BaseApiCodeAndUrl.TRACK_URL to "https://test-front-log-v1.starblink.co/app",
        BaseApiCodeAndUrl.ENABLE to true,
        BaseApiCodeAndUrl.SITE to SITE_DEFAULT
    )

    // dev 开发环境
    private val devEnv = mapOf(
        BaseApiCodeAndUrl.NAME to "dev",
        BaseApiCodeAndUrl.DESC to "开发环境",
        BaseApiCodeAndUrl.HOST to "https://guang-dev.starblink.co",
        BaseApiCodeAndUrl.URL to "https://guang-dev.starblink.co/graphql",
        BaseApiCodeAndUrl.LOG_URL to "https://dev-front-log.starblink.co/app",
        BaseApiCodeAndUrl.H5_HOST to "https://dev-getguang-com.starblink.co/",
        BaseApiCodeAndUrl.TRACK_URL to "https://dev-front-log-v1.starblink.co/app",
        BaseApiCodeAndUrl.ENABLE to true,
        BaseApiCodeAndUrl.SITE to SITE_DEFAULT
    )


    /// 美国配置
    private val usSiteEvn = mapOf(
        BaseApiCodeAndUrl.NAME to "pub",
        BaseApiCodeAndUrl.DESC to "生产环境",
        BaseApiCodeAndUrl.HOST to "https://us-guang.starblink.co",
        BaseApiCodeAndUrl.URL to "https://us-guang.starblink.co/graphql",
        BaseApiCodeAndUrl.LOG_URL to "https://us-front-log.starblink.co/app",
        BaseApiCodeAndUrl.H5_HOST to "https://us-www.getguang.com/",
//        BaseApiCodeAndUrl.TRACK_URL to "https://us-front-log-v1.starblink.co/app",
        BaseApiCodeAndUrl.TRACK_URL to US_PUB_TRACK_URL,
        BaseApiCodeAndUrl.ENABLE to true,
        BaseApiCodeAndUrl.SITE to SITE_DEFAULT
    )

    var standardCfgSet = hashMapOf(
        ApiSiteEnum.GB.name to pubEnv,
        ApiSiteEnum.PUB.name to usSiteEvn,
        ApiSiteEnum.PRE.name to preEnv,
        ApiSiteEnum.TEST.name to testEnv,
        ApiSiteEnum.DEV.name to devEnv
    )


    var svrApiCfgEnv: Map<String, Any> = mapOf()

//    //支持基础库自定义域名配置
//    fun onInit(ctx: Context, standardCfgSet: HashMap<String, Map<String, Any>>) {
//        this.standardCfgSet = standardCfgSet
//        onInit(ctx, DEFAULT_FLAVOR)
//    }

    fun onInit(ctx: Context, flavor: String) {
        val mmkvEnvChoice = SkStorage.getString(GuangConfig.CURRENT_ENV_9527, null)
        svrApiCfgEnv = if (mmkvEnvChoice != null) {
            standardCfgSet[mmkvEnvChoice] ?: getDefaultApiEnvFromJsonFile(ctx, flavor)
        } else {
            getDefaultApiEnvFromJsonFile(ctx, flavor)
        }
    }



    private fun getDefaultApiEnvFromJsonFile(ctx: Context, flavor: String): Map<String, Any> {
        //读本地json配置
        val netCfgJsonStr = readText4Assets(ctx, "net_cfg/nef_cfg.json")
        val netCfgList: ArrayList<String>?
        //默认读不到则为标准生产环境
        var topConfigStr = if (flavor == DEFAULT_FLAVOR) "pub" else "test"
        //1.5版本默认优先选择美国为默认站点
        svrApiCfgEnv = if (flavor == DEFAULT_FLAVOR) usSiteEvn else testEnv
        if (netCfgJsonStr != null) {
            //JSON转list
            netCfgList =
                Gson().fromJson(
                    netCfgJsonStr,
                    object : TypeToken<ArrayList<String>>() {}.type
                )
            if (netCfgList != null && netCfgList.size > 0) {
                topConfigStr = netCfgList[0]
            }
        }
        standardCfgSet.forEach { it ->
            //匹配读取到的配置 转大写
            if (it.key == topConfigStr.uppercase()) {
                svrApiCfgEnv = it.value
            }
        }
        SkStorage.put(GuangConfig.CURRENT_ENV_9527, topConfigStr.uppercase())
        return svrApiCfgEnv
    }


    /**
     * 读取assets中的【文本文件】内容
     */
    private fun readText4Assets(ctx: Context, fileName: String): String? {
        var text: String? = null
        try {
            ctx.assets.open(fileName).use { ins ->
                BufferedInputStream(ins).use { bis ->
                    text = bis.reader().readText()
                }
            }
        } catch (_: Exception) {
        }
        return text
    }
}